<?php
/**
 * Created by PhpStorm.
 * User: qv
 * Date: 2018/7/27 0027
 * Time: 10:44
 */

namespace Database\base;

trait DbEvent
{

    private $_events = [];

    /**
     * @param $event
     * @param $callback
     * @param $params
     * @param bool $isAppend
     * @return $this
     */
    public function add($event, $callback, $params, $isAppend = FALSE)
    {
        if (!isset($this->_events[$event]) || !is_array($this->_events[$event])) {
            $this->_events[$event][] = [$callback, $params];
        } else {
            if ($isAppend) {
                array_unshift($this->_events[$event], [$callback, $params]);
            } else {
                $this->_events[$event][] = [$callback, $params];
            }
        }

        return $this;
    }

    /**
     * @param $event
     * @return bool
     */
    public function trigger(string $name)
    {
        if (!isset($this->_events[$name])) {
            return TRUE;
        }
        foreach ($this->_events[$name] as $val) {
            list($callback, $params) = $val;
            if (!call_user_func($callback, ...$params)) {
                unset($this->_events);
                return FALSE;
            }
        }
        return TRUE;
    }

    /**
     * @param $name
     * @param null $handler
     * @return $this
     */
    public function off($name, $handler = NULL)
    {
        if (!isset($this->_events[$name])) {
            return $this;
        }
        if ($handler === NULL) {
            unset($this->_events[$name]);
        } else {
            $events = $this->_events[$name];
            foreach ($events as $key => $val) {
                if ($handler === $val[0]) {
                    unset($events[$key]);
                    break;
                }
            }
            $this->_events[$name] = $events;
        }

        return $this;
    }
}